import React, { useState, useRef } from 'react';
import { Dialog, Form, Input, Button, Switch, Select, Field } from '@alifd/next';
import { IPublicModelPluginContext, IPublicModelResource } from '@alilc/lowcode-types';
import { isDef } from './shared/functions';
import { getProjectSchema, saveSchema, removeSchema, saveWorkspaceSchema } from '@/services/mockService';

const formItemLayout = {
  labelCol: { span: 5, },
  wrapperCol: { span: 19, }
};

class Controller {
  pluginContext?: IPublicModelPluginContext;
  pluginHidePanel = () => {};
  dialogInstance: any;
  resource?: Array<{ id: string, slug: string, title: string, path: string }>;

  init = (ctx: IPublicModelPluginContext) => {
    this.pluginContext = ctx;
    const { skeleton }: any = ctx;
    // 这块很有意思哟，原型的知识
    this.pluginHidePanel = () => skeleton.hidePanel('ViewManagerPane');
  }

  formPage = function (props: { templateList : Array<any>, ctx: any }) {
    const { templateList, ctx } = props;
    const customTemplateDisabled = !templateList.length;

    const [customTemplate, setCustomTemplate] = useState<boolean>(false);
    const [title, setTitle] = useState<string | undefined>();
    const [slug, setSlug] = useState<string | undefined>();
    const [path, setPath] = useState<string | undefined>();
    // @ts-ignore
    // const fieldRef = useRef(new Field(this));
    
    const customTemplateChangeHandle = (checked: boolean) => {
      setCustomTemplate(checked);
    }
    
    const checkSlug = (rule: any, value: any, callback: any) => {
      if (templateList.some((item: any) => item.slug === value)) {
        return callback("页面标识必须唯一，请尝试替换");
      }
      callback();
    };

    const checkPath = (rule: any, value: any, callback: any) => {
      if (templateList.some((item: any) => item.path === value)) {
        return callback("页面路由必须唯一，请尝试替换");
      }
      callback();
    };

    const onSubmit = async (values: any, errors: any) => {
      console.log(values, errors, ctx.pluginContext);
      if (isDef(errors)) {
        return;
      }
      const { customTemplate, template, title, slug, path } = values;
      const list = ctx.pluginContext?.workspace.resourceList.map((d: any) => d.options) || [];
      list?.push({
        slug,
        title,
        id: slug,
        path,
      });
      ctx.pluginContext?.plugins.pluginResourceData.update(list);
      const resource = (ctx.pluginContext?.workspace.resourceList|| []).filter((d: any) => d.id === values.slug)?.[0];
      ctx.pluginContext?.workspace.openEditorWindow(resource);
      const window = ctx.pluginContext?.workspace.windows.find((item: any) => item.resource.options.id === slug);
      setTimeout(async () => {
        const windowCtx = window[Object.getOwnPropertySymbols(window)[0]]['editorView'];
        console.log('window', window, windowCtx, ctx.pluginContext);
        if (customTemplate) {
          const scenarioName = ctx.pluginContext?.config.get('scenarioName');
          const schema = await getProjectSchema(scenarioName, template);
          // 加载 schema
          window.importSchema(schema as any);
          window.simulatorHost?.rerender();
        }
        setTimeout(() => {
          // 保存当前window的schema
          saveSchema(slug, windowCtx);
          // 保存当前应用的schema
          saveWorkspaceSchema(ctx.pluginContext);
        }, 50)
      }, 0);
      ctx.dialogInstance?.hide();
      ctx.pluginHidePanel();
    };

    return (
      <Form
        {...formItemLayout}
        style={{ width: "500px" }}
        colon 
        // field={fieldRef.current}
      >
        <Form.Item
          name="customTemplate"
          label="自定义模板"
          required
        >
          <Switch autoWidth disabled={customTemplateDisabled} checked={customTemplate} onChange={customTemplateChangeHandle} />
        </Form.Item>
        {
          customTemplate && (
            <Form.Item
              name="template"
              label="模板"
              required
            >
              <Select
                placeholder="请选择模板"
                style={{ width: '100%' }}
              >
               {
                templateList.map((item: any) => <Select.Option value={item.slug}>{item.title}</Select.Option>)
               }
              </Select>
            </Form.Item>
          )
        }
        <Form.Item
          name="title"
          label="页面标题"
          required
        >
          <Input value={title} onChange={setTitle}/>
        </Form.Item>
        <Form.Item
          name="slug"
          label="页面标识"
          required
          validator={checkSlug}
        >
          <Input value={slug} onChange={setSlug}/>
        </Form.Item>
        <Form.Item
          name="path"
          label="页面路由"
          required
          validator={checkPath}
        >
          <Input value={path} onChange={setPath} />
        </Form.Item>
        <Form.Item label="" colon={false}  wrapperCol={{ offset: 5 }}>
          <Form.Submit
            type="primary"
            validate
            onClick={onSubmit}
            style={{ marginRight: 8 }}
          >
            确认
          </Form.Submit>
          <Button onClick={() => {
            ctx.dialogInstance?.hide();
          }}>取消</Button>
        </Form.Item>
      </Form>
    )
  }
  
  onAddPage = () => {
    const templateList = this.pluginContext?.workspace.resourceList.map(d => d.options) || [];
    this.dialogInstance = Dialog.show({
      v2: true,
      title: "新增页面",
      content: <this.formPage
        templateList={templateList}
        ctx={this}
      />,
      footerActions: [],
    })
  }

  onDeletePage = async (resource: IPublicModelResource) => {
    Dialog.show({
      v2: true,
      title: "删除页面",
      content: `删除页面后无法恢复，是否确定删除页面 ${resource.options.title}.`,
      onOk: () => {
        this.pluginContext?.workspace.removeEditorWindow(resource.name!, resource.options.id);
        const list = this.pluginContext?.workspace.resourceList.map(d => d.options);
        const newList = list?.filter(d => d.id !== resource.options.id);
        this.pluginContext?.plugins.pluginResourceData.update(newList);
        removeSchema(resource.options.id, this.pluginContext);

        const resourceList = this.pluginContext?.workspace.resourceList;
        const curResource = resourceList ? resourceList[resourceList.length - 1] : null;
        curResource && this.pluginContext?.workspace.openEditorWindow(curResource);
      },
    })
  }
}

export default new Controller();
